package com.hzhc.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.hzhc.common.SSLClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @program: cxportsys
 * @description: 获取token
 * @author: wxk
 * @create: 2020-06-16 13:54
 **/
@Component
public class HttpsPostUtil {

    private static String charset = "utf-8";


   /* public void setWxpUrl(String surl){
        xgUrl = surl;
    }*/

    public static String sendPost(String jsonStr,String xgUrl) {
        //获取token
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(xgUrl);
            //设置参数
            if(StrUtil.isNotBlank(jsonStr)){
                StringEntity entity = new StringEntity(jsonStr, "UTF-8");
                // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
                httpPost.setEntity(entity);
            }
            httpPost.addHeader("Content-Type","application/json");
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                org.apache.http.HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    public static String sendHttpsPostJSON(String url, JSONObject params, HttpHeaders headers) {
        RestTemplate client = restTemplateHttps();
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(params,headers);
        ResponseEntity<String> response =  client.postForEntity(url,requestEntity,String.class);
        return response.getBody();
    }

    public static RestTemplate restTemplateHttps()  {
        RestTemplate restTemplate = null;
        try {
            TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

            HttpClientBuilder clientBuilder = HttpClients.custom();

            CloseableHttpClient httpClient = clientBuilder.setSSLSocketFactory(sslsf).build();

            HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
            httpRequestFactory.setConnectionRequestTimeout(30000);
            httpRequestFactory.setConnectTimeout(30000);
            httpRequestFactory.setReadTimeout(30000);

            httpRequestFactory.setHttpClient(httpClient);

            restTemplate = new RestTemplate(httpRequestFactory);
            //解决乱码
            List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
            httpMessageConverters.forEach(httpMessageConverter ->{
                if(httpMessageConverter instanceof StringHttpMessageConverter){
                    StringHttpMessageConverter messageConverter = (StringHttpMessageConverter)httpMessageConverter;
                    messageConverter.setDefaultCharset(StandardCharsets.UTF_8);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return restTemplate;
    }

    public static String sendPost(String jsonStr, JSONObject jsonObject, String xgUrl) {
        //获取token
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(xgUrl);
            //设置参数
            if(StrUtil.isNotBlank(jsonStr)){
                StringEntity entity = new StringEntity(jsonStr, "UTF-8");
                // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
                httpPost.setEntity(entity);
            }
            httpPost.addHeader("Content-Type","application/json");
            for (String key:jsonObject.keySet()) {
                httpPost.addHeader(key, (String) jsonObject.get(key));
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                org.apache.http.HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }



    public static String doPostForUrl(String url){
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        //每个接口的Content-Type可能不同
//        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        try {
            HttpResponse response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return result;
        }
    }

    public static String sendRequest(String url, MultiValueMap<String,Object> params, HttpMethod method, HttpHeaders headers) {
        RestTemplate client = new RestTemplate();
        HttpEntity<MultiValueMap<String,Object>> requestEntity = new HttpEntity<>(params,headers);
        ResponseEntity<String> response =  client.exchange(url,method,requestEntity,String.class);
        return response.getBody();
    }

}
